import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:pax_info_app/model/clock.dart';
import 'package:pax_info_app/provider/provider_widget.dart';
import 'package:pax_info_app/repository/app_repository.dart';
import 'package:pax_info_app/ui/pages/login_page.dart';
import 'package:pax_info_app/ui/view_model/clock_list_model.dart';
import 'package:pax_info_app/utils/uidata.dart';
import 'package:table_calendar/table_calendar.dart';

class ClockListPage extends StatefulWidget {
  ClockListPage();

  @override
  _ClockListPageState createState() => _ClockListPageState();
}

class _ClockListPageState extends State<ClockListPage> {

  late ClockListModel _model;
  late DateTime _selectedDay;
  late DateTime _focusedDay;
  Clock? _curClock;
  late int _totalSalaryDays;

  @override
  void initState() {
    _totalSalaryDays = 0;
    _selectedDay = DateTime.now();
    _focusedDay = _selectedDay;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UIData.windowBg,
      appBar: AppBar(
        backgroundColor: const Color.fromRGBO(143, 148, 251, 1),
        title: const Text('考情自查'),
      ),
      body: ProviderWidget<ClockListModel>(
        model: ClockListModel(),
        onModelReady: (model) {
          model.initData();
          _model = model;
        },
        builder: (context, model, child) {
          _curClock = model.clock;

          return SingleChildScrollView(
            padding: const EdgeInsets.all(15.0),
            child: Column(
              children: [
                _buildTotalInfo(model),
                const SizedBox(height: 15.0,),
                _buildCalendar(model),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildTotalInfo(ClockListModel model) {
    return Card(
        color: Colors.white,
        elevation: 0.0, //设置阴影
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))), //设置圆角
        child: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('${_focusedDay.month}月汇总', style: const TextStyle(
                fontSize: 16.0,
                color: UIData.textNormal,
                fontWeight: FontWeight.bold,
              ),),
              const SizedBox(height: 10.0,),
              Row(
                children: [
                  _buildTotalItem('记薪天数(天)', '${model.totalSalaryDays}'),
                  _buildTotalItem('迟到(次)', '0'),
                  _buildTotalItem('早退(次)', '${model.totalLeaveEarlyDays}'),
                ],
              ),
            ],
          ),
        )
    );
  }

  Widget _buildTotalItem(String title, String value) {
    return Expanded(child: Column(
      children: [
        Text(value, style: const TextStyle(
          fontSize: 18.0,
          fontWeight: FontWeight.bold,
        ),),
        Text(title)
      ],
    ));
  }

  Widget _buildCalendar(ClockListModel model) {

    TextStyle _textStyle = const TextStyle(
      fontSize: 16.0,
    );
    return Card(
      color: Colors.white,
      elevation: 0.0, //设置阴影
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))), //设置圆角
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 5.0, vertical: 15.0),
        child: Column(
          children: [
            Row(
              children: [
                const SizedBox(width: 10.0,),
                RichText(text: TextSpan(
                    text: '每日记录',
                    style: const TextStyle(color: UIData.textNormal, fontSize: 16.0, fontWeight: FontWeight.bold),
                    children: <TextSpan> [
                      TextSpan(
                        text: ' （${_focusedDay.month}月）',
                        style: const TextStyle(
                            fontSize: 14.0, fontWeight: FontWeight.normal),
                      ),
                    ]
                )),
              ],
            ),
            const SizedBox(height: 10.0,),
            TableCalendar(
              locale: "zh_CN",
              headerVisible: false,
              firstDay: DateTime.utc(2010, 1, 1),
              lastDay: DateTime.now(),
              focusedDay: _focusedDay,
              onPageChanged: _onPageChanged,
              calendarBuilders: CalendarBuilders(
                markerBuilder: (context, date, _) {
                  String _date = formatDate(date, [yyyy, '-', mm, '-', dd]);
                  int index = model.list?.indexWhere((ele) => ele.fDate!.contains(_date))??-1;
                  Clock? _clock = index > -1 ? model.list![index] : null;
                  return Container(
                    decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: _clock != null && _clock.salaryDays != null && _clock.salaryDays! > 0
                            ? UIData.primaryColor : Colors.white), //Change color
                    width: 5.0,
                    height: 5.0,
                    margin: const EdgeInsets.symmetric(horizontal: 1.5),
                  );
                },
              ),
              calendarStyle: const CalendarStyle(
                  holidayTextStyle: TextStyle(color: Colors.red),
                  holidayDecoration: BoxDecoration(
                      color: Colors.transparent, shape: BoxShape.circle),
                  // Use `CalendarStyle` to customize the UI
                  outsideDaysVisible: true,
                  // outsideDecoration: BoxDecoration(
                  //   color: Colors.cyan,
                  // ),
                  markersMaxCount: 1,
                  // outsideDecoration: ,
                  // markerSize: 10,
                  // markersAlignment: Alignment.bottomCenter,
                  // markerMargin: EdgeInsets.only(top: 8),
                  // cellMargin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                  todayDecoration: BoxDecoration(
                    color: Color(0xffd8d7f5),
                    shape: BoxShape.circle,
                  ),

                  // markerSizeScale: 5,
                  markerDecoration:
                  BoxDecoration(color: Colors.cyan, shape: BoxShape.circle),
                  canMarkersOverflow: true),
              selectedDayPredicate: (day) {
                return isSameDay(_selectedDay, day);
              },
              onDaySelected: _onDaySelected,
            ),
            const Divider(),
            Container(
              padding: const EdgeInsets.all(15.0),
              child: Column(
                children: [
                  Row(
                    children: [
                      Text('上班', style: _textStyle,),
                      const SizedBox(width: 20.0,),
                      Text('${_curClock?.fAM}(${_curClock?.fAMType})', style: _textStyle,)
                    ],
                  ),
                  const SizedBox(height: 10.0,),
                  Row(
                    children: [
                      Text('下班', style: _textStyle,),
                      const SizedBox(width: 20.0,),
                      Text('${_curClock?.fPM}(${_curClock?.fPMType})', style: _textStyle,)
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _onPageChanged(focusedDay) async {
    setState(() {
      _focusedDay = focusedDay;
      _selectedDay = _focusedDay;
    });
    String _date = formatDate(focusedDay, [yyyy, '-', mm]);
    print('>>>>>> _focusedDay _date: $_date');
    _model.initData(fDate: _date);
  }
  
  _onDaySelected(selectedDay, focusedDay) async {
    setState(() {
      _selectedDay = selectedDay;
      _focusedDay = focusedDay; // update `_focusedDay` here as well
    });
    print('>>>>>> _selectedDay: $_selectedDay, _focusedDay: $_focusedDay');

    String _date = formatDate(_selectedDay, [yyyy, '-', mm, '-', dd]);
    print('>>>>>> _date: $_date');
    _curClock = await _model.getDetail(_date);
    setState(() {});
  }
}